package com.wz.jiangsu.main.lock;

public class Test {
    private static final Object lock = new Object();
    private static boolean isOddTurn = true; // 用于控制交替输出

    public static void main(String[] args) {
        Thread oddThread = new Thread(() -> getSize(9, true), "奇数线程");
        Thread evenThread = new Thread(() -> getSize(9, false), "偶数线程");

        oddThread.start();
        evenThread.start();
    }

    private static void getSize(int size, boolean isOdd) {
        synchronized (lock) {
            for (int j = 1; j <= size; j++) {
                if ((j % 2 != 0 && isOdd) || (j % 2 == 0 && !isOdd)) {
                    while ((isOdd && !isOddTurn) || (!isOdd && isOddTurn)) {
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            Thread.currentThread().interrupt();
                            return;
                        }
                    }

                    System.out.println((isOdd ? "奇数:" : "偶数:") + Thread.currentThread().getName() + " :" + j);
                    isOddTurn = !isOddTurn; // 切换输出权限
                    lock.notify(); // 唤醒其他线程
                }
            }
        }
    }
}